package com.chenzouquan.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class JsonToYamlConverter {
    String jsonFilePath = "path/to/json/file.json"; // JSON文件路径
    String yamlFilePath = "path/to/yaml/file.yaml"; // 要保存的YAML文件路径

    /**
     * json转yaml文件
     * @param jsonFilePath
     * @param yamlFilePath
     * @return
     */
    public  boolean change(String jsonFilePath, String yamlFilePath) {
        try {
            // 读取 JSON 文件
            ObjectMapper jsonMapper = new ObjectMapper();
            JsonNode rootNode = jsonMapper.readTree(new File(jsonFilePath));

            // 创建 YAML Mapper
            YAMLMapper yamlMapper = new YAMLMapper();

            // 将 JSON 转换为 YAML
            String yamlContent = yamlMapper.writeValueAsString(rootNode);

            // 将 YAML 内容写入文件
            File yamlFile = new File(yamlFilePath);
            yamlMapper.writeValue(yamlFile, yamlContent);

            System.out.println("JSON 文件成功转换为 YAML");
            // 删除原文件
            new File(jsonFilePath).delete();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 删除原文件
        new File(jsonFilePath).delete();
        return false;
    }

    private static Yaml createYaml() {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // 设置YAML的块样式
        return new Yaml(options);
    }
}
